import React from 'react';

// 导入头部组件
import {NavBar,Icon,PickerView} from 'antd-mobile';

// 导入搜索组件
import Search from '../Index/Module/Search';

// 导入样式
import Styles from './index.module.scss';

// 导入请求模块
import {request} from '../../utils/request';

// 导入react的长列表
import { List } from 'react-virtualized';

import HouseItem from '../components/HouseItem'
class Found extends React.Component {
  // 城市id
  cityId = '';
  pageSize = 20
  pageNum = {
    start:1,
    end:this.pageSize
  }
  // 请求的房源数据数量
  count = 0
  selectParams = {}
  isLoading = false
  state = { 
    filterData:[
      {id:1,label:'区域',cols:3},
      {id:2,label:'方式',cols:1},
      {id:3,label:'租金',cols:1},
      {id:4,label:'筛选'},
    ],
    ShowCenter:false,
    ShowSidebar:false,
    activeIndex:0,
    value:null,
    houseData:[],
    selectData:[[],[],[],[]],
    houseArray:[]
    }
   async componentDidMount(){
    // 页面加载 筛选的高亮不显示
    this.setState({
      activeIndex:-1
    })
    //  请求数据
     this.cityId = (await request.get('/area/info?name=广州')).data.body.value
    const res = (await request.get('/houses/condition?id=' + this.cityId)).data.body
    // 准备一个空的数组来存储请求回来的数据 按照需求来存放
    const houseData = []
    // 房源区域数据 数组第一项
    houseData[0] = [
      res.area,res.subway
    ]
    // 房源方式数据 数组第二项
    houseData[1] = res.rentType
    // 房源租金数据 数组第三项
    houseData[2] = res.price
    // 房源筛选数据 数组第四项
    houseData[3] = [
      {title:'户型',data:res.roomType},
      {title:'朝向',data:res.oriented},
      {title:'楼层介绍',data:res.floor},
      {title:'房屋亮点',data:res.characteristic},
    ]
    // 变更数据
    this.setState({
      houseData
    })
    // 页面加载获取一遍房源数据
    this.getHouseArray()
    
   }
   onChange = (value) => {
     const {selectData,activeIndex} = this.state
     selectData[activeIndex] = value
    this.setState({
      selectData
    });
  }
  //  点击筛选显示房源选择页面
  ShowFilter = (index) =>{
    this.setState({
      activeIndex:index
    })
    if(index >= 0 && index <= 2){
      this.setState({
        ShowCenter:true
      })
    }else if(index === 3){
        this.setState({
          // 侧边栏显示
          ShowSidebar:true,
          // 主筛选栏隐藏
          ShowCenter:false
        })
    }
  }
  // 点击遮罩层隐藏筛选框
  hiddenFilter = () => {
    this.setState({
      ShowCenter:false,
      ShowSidebar:false
    })
  }
  // 添加tag选项到数组中
  addTag = (value) => {
    const {selectData,activeIndex} = this.state
    // 判断数据是否重复 数组里面没有这个数据再添加
    const index = selectData[activeIndex].indexOf(value);
    if(index === -1){
    selectData[activeIndex].push(value)
    }else{
      selectData[activeIndex].splice(index,1)
    }
    this.setState({
      selectData
    })
  }
  // 处理筛选的数据并返回到后台
  getSelectParams = () =>{
    // 结构state数据
   const {selectData} = this.state
    // 点击筛选时初始化数组
   this.setState({
    houseArray:[]
  })
   this.pageNum.start = 1;
   this.pageNum.end = this.pageSize
    // 创建一个变量
    let selectParams = {}
    // 提取数组的第一项变成 key值
    const key = selectData[0][0]
    // 提取数组的第二项变成 value值
    const value = ['null',undefined,''].includes(selectData[0][2]) ? selectData[0][1] : selectData[0][2]
    // 将所有的数据拼接成对象的形式向后台发起请求
    selectParams = {
      [key]:value,
      rentType:selectData[1][0],
      price:selectData[2][0],
      more:selectData[3].join(',')
    }
    // 遍历对象 对象里面如果没有值就删除
    Object.keys(selectParams).forEach(key =>{
      if([undefined,'null',''].includes(selectParams[key])){
        delete selectParams[key]
      }
    })
    this.selectParams = selectParams
    // 发起请求
    this.getHouseArray()
    // 隐藏筛选框
    this.setState({
      ShowSidebar:false,
      ShowCenter:false
    })
  }
  // 筛选房源数据封装
  getHouseArray = async()=>{
    // 请求前将标记变为true
   this.isLoading = true
  //  const { selectParams } = this.state
   let res = (await request.get('/houses',{params:{ cityId:this.cityId, ...this.selectParams,...this.pageNum }})).data.body;
   this.count = res.count   
  this.setState({
    // 将旧数据与新数据一同结构重新排列
    houseArray:[...this.state.houseArray,...res.list]
  })
  // 请求完毕 将标记变成false
  this.isLoading = false
  }
  // 渲染长列表
  rowRenderer = ({index,key,style}) =>{
  return <div key={key} style={style}>
    <HouseItem item={this.state.houseArray[index]}></HouseItem>
  </div>
  }
  // 长列表滚动事件
  onScroll = ({scrollHeight,clientHeight,scrollTop})=>{
    // 计算出页面是否触底
    const isFirstRender = scrollHeight - clientHeight - scrollTop <= 60
    // 判断页面加载时长列表的高度是否为0
    const isRender = scrollHeight === 0
    // 当数据长度小于数据的总量是 停止请求
    const iSRequest = this.state.houseArray.length === this.count
    // 当页面快要到底部时触发请求 请求新数据并将其渲染
    // 长列表的最高高度为0时不要请求数据 停止执行下面代码
    if(!isFirstRender || isRender || this.isLoading) {
      return
    }
    if (iSRequest) {
      console.log(123);
      
    }
    // 请求新的数据 
    this.pageNum.start += this.pageSize
    this.pageNum.end += this.pageSize
    this.getHouseArray()
  }
  // 清除侧边栏数据
  clearTag = () => {
    const {selectData,activeIndex} = this.state
    selectData[activeIndex] = []
    this.setState({
      selectData,
      ShowSidebar:false
    })
  }
  render() { 
    const {filterData,ShowCenter,ShowSidebar,activeIndex,houseData,selectData,houseArray} = this.state
    return ( 
      <div>
         <NavBar
      mode="light"
      icon={<Icon type="left" />}
      onLeftClick={() => this.history.goBack()}
    >
      <Search></Search>
    </NavBar>
    {/* 筛选栏 开始*/}
    <div className={Styles.filter_title}>
      {
        filterData.map((item,index) => (
          <div key={item.id} onClick={()=> this.ShowFilter(index)} className={
            [Styles.fliter_item,
              activeIndex === index ? Styles.active : ''
            ].join(' ')
          }>{item.label} <i className='iconfont icon-arrow'></i></div>
        ))
      }
    </div>
     {/* 筛选栏 结束*/}
      {/* 筛选栏目主体 开始 */}
      {
        ShowCenter && 
        <div className={Styles.filter_center}>
      <div className={Styles.filter_body}>
        <div className={Styles.filter_content}>
        <PickerView
          onChange={this.onChange}
          value={selectData[activeIndex]}
          data={houseData[activeIndex]}
          cols={filterData[activeIndex].cols}
        />
        </div>
        <div className={Styles.filter_footer}>
          <span className={Styles.filter_cancel_btn} onClick={()=>this.hiddenFilter()}>取消</span>
          <span className={Styles.filter_confirm_btn} onClick={this.getSelectParams}>确定</span>
        </div>
      </div>
      <div onClick={()=> this.hiddenFilter()} className={Styles.mask}></div>
      </div>
      }
       {/* 筛选栏目主体 结束 */}
      {/* 侧边筛选栏 开始 */}
      {
        ShowSidebar && 
        <div className={Styles.filter_sidebar}>
        {/* 主体内容 */}
        <div className={Styles.filter_sildebar_body}>
        <div className={Styles.filter_sidebar_content}>
          {
            houseData[3].map(item=>(
            <div key={item.title} className={Styles.filter_sidebar_item}>
            <div className={Styles.filter_sidebar_titie}>{item.title}</div>
           <div className={Styles.filter_sidebar_tag}>
           {
             item.data.map((tag,index) => (
              <div key={index} 
              onClick={()=>this.addTag(tag.value)} 
              className={
                [
                Styles.filter_sidebar_label,
                selectData[activeIndex].includes(tag.value) ? Styles.tagactive : ''
                ].join(' ')
                }>
              {tag.label}
              </div>
             ))
           }
           </div>
          </div>
            ))
          }
        </div>
        <div className={Styles.filter_footer + ' ' + Styles.filter_sidebar_footer}>
          <span className={Styles.filter_cancel_btn} onClick={this.clearTag}>清除</span>
          <span className={Styles.filter_confirm_btn} onClick={this.getSelectParams}>确定</span>
        </div>
        </div>
        {/* 遮罩层 */}
        <div onClick={()=>this.hiddenFilter()} className={Styles.mask}></div>
      </div>
      }
      {/* 侧边筛选栏 结束 */}
      {/* 页面房源列表 开始 */}
      <div className="houuse_list">
        <List
        width={window.screen.width}
        height={window.screen.height - 45 - 45 - 50}
        rowCount={houseArray.length}
        rowHeight={108}
        rowRenderer={this.rowRenderer}
        onScroll={this.onScroll}
        ></List>
      </div>
      {/* 页面房源列表 结束 */}
      </div>
     );
  }
}
 
export default Found;